<template>
  <div class="commodity-dialog">
    <el-dialog
      :title="type === '1'?'添加':'编辑'"
      :visible.sync="dialogVisible"
      @close="closeDialog">
      <el-form ref="form" :model="paramForm" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="paramForm.name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="paramForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input type="textarea" v-model="paramForm.describes"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {postRequest} from '../../util/http'
export default {
  name: 'CommodityDialog',
  data () {
    return {
      dialogVisible: true,
      type: this.$route.query.type,
      paramForm: {
        id: this.$route.query.id,
        name: '',
        price: '',
        describes: ''
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    // 初始化方法
    init () {
      // type:1添加，2编辑
      if (this.type !== '1') {
        this.view()
      }
    },
    // 关闭弹窗回调方法
    closeDialog () {
      this.$router.push({path: '/commodity/list'})
    },
    // 保存或更新
    async save () {
      let res = await postRequest(this.type === '1' ? '/commodity/save' : '/commodity/update', this.paramForm)
      if (res.errorCode === 200 && res.data) {
        this.$message({
          message: this.type === '1' ? '添加成功' : '编辑成功',
          type: 'success'
        })
        this.dialogVisible = !this.dialogVisible
      }
    },
    // 详情
    async view () {
      let res = await postRequest('/commodity/view', {id: this.paramForm.id})
      if (res.errorCode === 200 && res.data) {
        this.paramForm = res.data
      }
    }
  }
}
</script>

<style>

</style>
